package com.nexgo.payment.pack;

import com.nexgo.common.ByteUtils;
import com.nexgo.data.XMLData;
import com.nexgo.data.entity.SendData;
import com.nexgo.data.entity.SendDataBuilder;
import com.nexgo.data.json.JsonSendData;
import com.nexgo.data.json.JsonTools;
import com.nexgo.data.json.bean.JsonBody;
import com.nexgo.data.json.bean.SendBodyData;
import com.nexgo.data.json.bean.SendHead;
import com.nexgo.payment.constrant.PreferencesConstants;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.entity.MessageData;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.util.MessageHelper;
import com.nexgo.payment.util.StringUtils;
import com.nexgo.payment.util.XmlUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 扫码支付
 * Created by wanghongyang on 2017/9/1.
 */
class ScanOrderBuilder extends DataBuilder{
    private Logger log;

    ScanOrderBuilder(TransData transData, DataSource repository) {
        super(transData, repository);
        log = LoggerFactory.getLogger(this.getClass().getName());
    }

    @Override
    public SendData form() {
        SendData sendData = new SendDataBuilder().setListener(mListener).setSignListener(mSignListener).createSendData();
        sendData.setHeader(MessageHelper.formMessageHeader(mRepository.getParamValue(PreferencesConstants.TPDU)));
        sendData.setMsgType(mTransData.getTransType().getMsgType());
        sendData.setProcCode(mTransData.getTransType().getProcCode());
        sendData.setAmount(StringUtils.leftPad(mTransData.getAmount(), 12, '0'));
        sendData.setTraceNum(mRepository.getParamValue(PreferencesConstants.TRACE_NUMBER));
        setCurruntTraceNumber(mRepository.getParamValue(PreferencesConstants.TRACE_NUMBER));
        mTransData.setOrgTraceNum(mRepository.getParamValue(PreferencesConstants.TRACE_NUMBER));
        mTransData.setOrgBatchNum(mRepository.getParamValue(PreferencesConstants.BATCH_NUMBER));
        mRepository.increaseTraceNumber();
//        sendData.setEntryMode(mTransData.getEntryMode());
//        sendData.setConditionCode(mTransData.getTransType().getConditionCode());

        sendData.setTerminalId(mRepository.getParamValue(PreferencesConstants.TERMINAL_ID));
        sendData.setMerchantId(mRepository.getParamValue(PreferencesConstants.MERCHANT_ID));
        sendData.setAdditionalData(formField48());
        sendData.setFundType(mTransData.getFundType());

        sendData.setField60(formField60());
        sendData.setField62(formField62());
        sendData.setMac("0000000000000000");
        return sendData;
    }

    @Override
    public MessageData formJsonData() {
        MessageData sSendData = new MessageData();
        JsonSendData jsonSendData = new JsonSendData();
        SendHead head = new SendHead();
        JsonBody jsonBody = new JsonBody();

        //head
        head.setTRAN_PROCESS("");
        head.setTRAN_ID("");
        head.setTranscode("CIPP010102");
        String date = new SimpleDateFormat("yyyyMMddHHmmss", SysConstant.LOCALE).format(new Date());
        head.setTerm_trans_time(date);
        head.setMcht_id(mRepository.getParamValue(PreferencesConstants.MERCHANT_ID));
        //经纬度，签名暂时为空
        head.setLngx(mRepository.getParamValue(PreferencesConstants.LONGITUDE));
        head.setLngy(mRepository.getParamValue(PreferencesConstants.LATITUDE));
        head.setSign("0000000000000000");
        jsonSendData.setREQ_HEAD(head);


        SendData sendData  = new SendDataBuilder().setListener(mListener).setSignListener(mSignListener).createSendData();
        sSendData.setSendData(sendData);

        //body
        jsonBody.setTotal_amount(mTransData.getAmount());
        jsonBody.setAmount_type("156");
        jsonBody.setChannel(mTransData.getScanChannel());
        jsonBody.setTerm_id(mRepository.getParamValue(PreferencesConstants.TERMINAL_ID));
        jsonBody.setTerm_batch_no(mRepository.getParamValue(PreferencesConstants.BATCH_NUMBER));
        jsonBody.setTerm_pos_no(mRepository.getParamValue(PreferencesConstants.TRACE_NUMBER));
        mTransData.setOrgBatchNum(mRepository.getParamValue(PreferencesConstants.BATCH_NUMBER));
        mTransData.setOrgTraceNum(mRepository.getParamValue(PreferencesConstants.TRACE_NUMBER));
        mRepository.increaseTraceNumber();
        jsonBody.setSpbill_create_ip("127.0.0.1");
        jsonBody.setAuth_code(mTransData.getPayCodeNo());

        SendBodyData sendBodyData = new SendBodyData();
        String str = JsonTools.toJson(jsonBody);
        sendBodyData.setDECRYPT(str);

        jsonSendData.setREQ_BODY(sendBodyData);

        sSendData.setJsonSendData(jsonSendData);

        setScan(true);

        return sSendData;
    }
    private String formField60() {
        StringBuilder sb = new StringBuilder();
        sb.append(String.format(SysConstant.LOCALE, "%02d",
                Integer.parseInt(StringUtils.firstNonEmpty(mRepository.getParamValue(PreferencesConstants.CURRENT_OPERATOR_NO), "1"))));
        sb.append("0000");
        sb.append("6");
        sb.append(mTransData.isFallback() ? "2" : "0");
        return ByteUtils.byteArray2HexString(sb.toString().getBytes());
    }

    private String formField48() {
        StringBuilder sb = new StringBuilder();

        Map<String, String> xmlMap = new HashMap<>();
        XMLData xmlData = new XMLData();

        //head
        xmlData.setTranscode("CIPP010102");
        String date = new SimpleDateFormat("yyyyMMddHHmmss", SysConstant.LOCALE).format(new Date());
        xmlData.setTerm_trans_time(date);
        xmlData.setMcht_id(mRepository.getParamValue(PreferencesConstants.MERCHANT_ID));
        //body
        xmlData.setTotal_amount(mTransData.getAmount());
        xmlData.setAmount_type("156");
        xmlData.setChannel(mTransData.getScanChannel());
        xmlData.setTerm_id(mRepository.getParamValue(PreferencesConstants.TERMINAL_ID));
        xmlData.setTerm_batch_no(mRepository.getParamValue(PreferencesConstants.BATCH_NUMBER));
        xmlData.setTerm_pos_no(getCurruntTraceNumber());
        xmlData.setSpbill_create_ip("127.0.0.1");

        sb.append(XmlUtils.formXML(xmlData));



        return sb.toString();
    }


    private String formField62() {
        StringBuilder sb = new StringBuilder();
//        sb.append(mTransData.getTransType().getFuncCode());
        sb.append(mRepository.getParamValue(PreferencesConstants.BATCH_NUMBER));
        sb.append(getCurruntTraceNumber());
        return sb.toString();
    }

    /**
     * 组银联F59 21号文相关的
     */
  /*  private String formField59() {
        StringBuilder sb = new StringBuilder();
        String tagA2 = formA2();
        if(!TextUtils.isEmpty(tagA2)) {
            sb.append(formTLV("A2", tagA2));
        }
        //TAG A3 - 扫码付信息域
        String tagA3 = mTransData.getPayCodeNo();
        if(!TextUtils.isEmpty(tagA3)) {
            sb.append(formTLV("A3", tagA3));
        }
        return ByteUtils.byteArray2HexString(sb.toString().getBytes());
    }

    private String formA2(){
        String payCodeNo = mTransData.getPayCodeNo();
        if (TextUtils.isEmpty(payCodeNo)) return "";

        String randFact;
        String manufacturer = "000004";
        String terminalType;
        String uniqueCode;
        String encryptedUniqueCode;

        randFact = payCodeNo.substring(payCodeNo.length() - 6);
        HSMDevice hsmDevice = ApiDeviceEngine.getInstance().getHSMDevice();
        TusnData terminalUniqueCode  = hsmDevice.getTUSN(0, randFact.getBytes());
        //POS机不支持,直接返回
        if (terminalUniqueCode == null) return "";

        terminalType = terminalUniqueCode.getTerminalType();
        uniqueCode = terminalUniqueCode.getTusn();              //银联序列号
        encryptedUniqueCode = terminalUniqueCode.getMac();
        log.debug("随机因子:" + randFact);
        log.debug("厂家编号:" + manufacturer);
        log.debug("终端类型:" + terminalType);
        log.debug("唯一硬件序列号:" + uniqueCode);
        log.debug("唯一硬件序列号密文:" + encryptedUniqueCode);

        StringBuilder sb = new StringBuilder();
        //TAG01-设备类型   TLV
        if(TextUtils.isEmpty(terminalType)){
            terminalType = "04";
        }
        sb.append(formTLV("01", terminalType));
        //TAG02-终端硬件序列号  TLV
        if(!TextUtils.isEmpty(uniqueCode)){
            sb.append(formTLV("02", uniqueCode));
        }
        //TAG03-加密随机因子
        if(!TextUtils.isEmpty(randFact)){
            sb.append(formTLV("03", randFact));
        }
        //TAG04-硬件序列号密文数据
        if(!TextUtils.isEmpty(encryptedUniqueCode)){
            sb.append(formTLV("04", encryptedUniqueCode));
        }
        //TAG05-应用程序版本号
        String appVersionNo = "20170901";
        sb.append(formTLV("05",appVersionNo));
        return sb.toString();
    }

    *//**
     * 组59域TLV格式数据
     *
     * @param tag 标签
     * @param value 值
     * @return 返回tlv格式数据
     *//*
    private String formTLV(String tag, String value){
        if(TextUtils.isEmpty(tag) || TextUtils.isEmpty(value)){
            return "";
        }
        try {
            StringBuilder sb = new StringBuilder();
            sb.append(tag);
            sb.append(new Formatter().format("%03d", value.length()).toString());
            sb.append(value);
            return  sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }*/
}
